<?php
/*
 *   This file is part of Verbum.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 *   Copyright (c) 2008 Sergio Gabriel Teves <gabriel.sgt at gmail.com>
 * 
 */

	function isEmpty($obj) {
		return (trim($obj)=='');
	}

	function isValidEmail($email) 
	{
	   return ereg("^[^@ ]+@[^@ ]+\.[^@ ]+$", $email);
	}
	
	function validCredentials($user,$func) {
		global $CREDENTIALS;
		if (!isset($user) or $user==null) {
			return false;
		} else {
			$arr = $CREDENTIALS[$user->groupid];
			if ($func=='') return true;
			return in_array($func,$arr);
		}
	}
	
	function saveCookie($var, $value) {
		setcookie($var,$value,time()+((COOKIE_EXPIRE*24)*60*60));
	}

	function stringToBytes($var) {
		$v = strtoupper($var[strlen($var)-1]);
		$s = substr($var, 0 ,strlen($var)-1);
		switch ( $v ) {
			case "G":
				$s *= 1024;
			case "M":
				$s *= 1024;
			case "K":
				$s *= 1024;
			case "B":
				break;
			default:
				$s = $var;
				break;
		} 
		return $s;
	}
	/* I NEED TO KEEP THE KEYS */
    function arrayRemove(&$array, $value) {
    	$key = array_search($value,$array);
    	if ($key) {
    		$ar = array();
    		foreach ($array as $k => $v) {
    			if ($v!=$value) {
    				$ar[$k]=$v;
    			}
    		}
    		$array=$ar;
    	}
    	/*
		$key = array_search($value,$array);
		if ($key) {
			$values = array_values($array);
			$idx = array_search($value,$values);
			$values[$idx] = array_pop($values);
			$array = $values;
		}*/
    }
    	
	function arrayCopy($org,&$dest,$incfields=null,$excfields=null) {
		foreach ($org as $k => $v) {
			if (isset($incfields)) {
				if (in_array($k,$incfields)) {
					$dest[$k]=$v;
				}
			} else if (isset($excfields)) {
				if (in_array($k,$excfields)) {
					$dest[$k]=$v;
				}				
			} else {
				$dest[$k]=$v;
			}
		}
	}
	
	/*
	 * Parse a simple key, value array or object
	 */
	function jsonArray($array, $key, $value) {
		global $_log;
		$res = "";
		foreach ($array as $ob) {
			if ($res!="") $res.=",";
			if (is_object($ob)) {
				$p = get_object_vars($ob);
				//$val = $p[$key];
				$res .= "['".$p[$key]."','".$p[$value]."']";						
				//$res .= "['".$ob->obj_array[$key]."','".$ob->obj_array[$value]."']";
			} else {
				$res .= "['$ob[$key]','$ob[$value]']";	
			}
		}
		return "[$res]";
	}

	function jsonformat($key,$value,$quote=true) {
		if ($quote) {
			return "\"".$key."\":\"".$value."\"";	
		} else {
			if (is_bool($value)) {
				if ($value==true) {
					return "\"".$key."\": true";		
				} else {
					return "\"".$key."\": false";
				}
			} else {
				return "\"".$key."\":".$value;
			}
			
		}
	}

	function jsonEncodeList($array, $fields, $values = null) {
		global $_log;
		$res="";
		foreach ($array as $ob) {
			if ($res!="") $res.=",";
			$fset = "";
			for ($i=0;$i<count($fields);$i++) {
				$data=false;
				$ar=false;
				$html = false;
				$enc = false;
				$bool=false;
				$f = $fields[$i];
				//$_log->debug(substr($f,0,1));
				if (substr($f,0,1)=="&") {
					$data=true;
					//$_log->debug("data = true");
					$f=substr($f,1);
				}
				if (substr($f,0,1)=="@") {
					$ar=true;
					$data=true;
					//$_log->debug("array = true");
					$f=substr($f,1);
				}
				if (substr($f,0,1)=="#") {
					$enc=true;
					//$_log->debug("enc = true");	
					$f=substr($f,1);
				}
				if (substr($f,0,1)=="%") {
					$html=true;
					//$_log->debug("html = true");	
					$f=substr($f,1);
				}
				if (substr($f,0,1)=="~") {
					$bool=true;
					$data=true;
					$f=substr($f,1);
				}
				if ($fset!="") $fset.=",";
				if (is_object($ob)) {
					if ($values != null) {
						//if (isset($ob->obj_array)) {
							//$val = $ob->obj_array[$values[$i]];
						//} else {
							$p = get_object_vars($ob);
							$val = $p[$values[$i]];	
						//}
					} else {
						//if (isset($ob->obj_array)) {
							//$val = $ob->obj_array[$f];
						//} else {
							$p = get_object_vars($ob);
							$val = $p[$f];
						//}
					}
				} else {
					if ($values != null) {
						$val = $ob[$values[$i]];
					} else {
						$val = $ob[$f];
					}
				}
				if ($enc) $val = jsAddSlashes(util::decode($val,false));
				if ($html) $val = htmlspecialchars($val);
				if ($ar) $val = json_encode($val);
				if ($bool) {
					if ($val==true) {
						$val=true;
					} else {
						$val=false;
					}
				}
				//$_log->debug("After ".$val);
				$fset .= jsonformat($f,$val,!$data);
			}
			$res .="{".$fset."}";
		}		
		return $res;
	}

	/*
	 * For class list. Return a json formated list with the object fields
	 */
	function jsonList($array, $fields, $values = null, $total = null) {
		$res = jsonEncodeList($array,$fields,$values);
		$m = "\"results\":[".$res."]";
		global $_log;
		if ($total!==null) {
			$m .= ",\"totalCount\":\"".$total."\"";	
		}
		return jsonReturn($m);
	}
	
	function jsonReturn($m) {
		return "{".$m."}";
	}
		
	function getTranslatedList($array) {
		for ($i=0;$i<count($array);$i++) {
			$array[$i]=s($array[$i]);
		}
		return util::arrayToString($array,",",true);;
	}

	function success($msg,$quote=true) {
		if (isset($msg)) {
			if ($quote) {
				out("{success: true, ret: '".addslashes($msg)."'}");	
			} else {
				out("{success: true, ret: ".$msg."}");
			}
			
		} else {
			out("{success: true}");	
		}
	}
	
	function failed($msg,$ret=null) {
		$str = "success: false, error: '".addslashes($msg)."'";
		if ($ret!=null) $str.=", ret: ".$ret;
		out("{".$str."}");		
	}
	
	function createMessageKey($string, $array) {
		foreach ($array as $key => $value) {
			$string = str_replace("{".$key."}", $value, $string);
		}
		return $string;
	}
	
	function inArray($array,$key,$value,$key2,$value2) {
		//global $_log;
		//$_log->debug("[inArray] value: ".$value);
		//$_log->debug($array);
		foreach ($array as $ob) {
			if (isset($key2) && isset($value2)) {
				if ($ob->obj_array[$key]==$value && $ob->obj_array[$key2]==$value2) {
					return $ob;
				}
			} else {
				if ($ob->obj_array[$key]==$value) {
					return $ob;
				}
			}
		}
		return false;
	}
	
	function findObject($array,$obj) {
		foreach ($array as $ob) {
			$a = 0;
			foreach ($obj as $k => $v) {
				if (is_object($ob)) {
					if ($ob->obj_array[$k]==$v) {
						$a++;
					}
				} else {
					if ($ob[$k]==$v) {
						$a++;
					}
				}
			}
			if ($a==count(array_keys($obj))) {
				return $ob;
			}
		}
		return false;
	}
	
	function out($t) {
		global $_log;
		global $TRANSID;
		$_log->debug("OUTPUT: ".$t);
		echo $t;
	}
	
	function getTeamId($u) {
		if ($u->groupid==GROUP_ADMIN) {
			return $_COOKIE['verbum']['team'];
		} else {
			return $u->teamid;
		}
	}
	
	function getLoginCredentials() {
		$logininfo = new stdClass;
		$logininfo->userid=$_COOKIE['verbum']['id'];
		$logininfo->pass=$_COOKIE['verbum']['uid'];
		return $logininfo;
	}
	
	function setLoginCredentials($us) {
		global $_log;
		$_log->debug("Set login credentials");
		setcookie('verbum[id]',$us->userid,time()+(60*60*24*COOKIE_EXPIRE));
		setcookie('verbum[uid]',$us->currentpwd,time()+(60*60*24*COOKIE_EXPIRE));		
	}

	function clearLoginCredentials() {
		global $_log;
		$_log->debug("Clear login credentials");
		setcookie('verbum[id]',"",-1);
		setcookie('verbum[uid]',"",-1);		
	}
	
	function jsAddSlashes($str) {
		global $_log;
		
		//$pattern = array("/\\\\/","/\n/", "/\r/","/\'/","/\"/");
		//$replace = array("\\\\\\\\","\\\\\\n" , "\\r","\\\'","\\\"");
		$pattern = array("/\\\\/","/\n/", "/\r/","/\"/");
		$replace = array("\\\\\\\\","\\\\\\n" , "\\r","\\\"");
		
	    //$pattern = array("/\\\\/",   "/\n/", "/\r/", "/\"/", "/\'/", "/&/");
	    //$replace = array("\\\\\\\\", "\\n" , "\\r" , "\\\"", "\\'" , "\\x26");
	    $r = preg_replace($pattern, $replace, $str);
	    return $r;
	}
	
	function jsCleanSlashes($str) {
		$pattern = array("\\n", "\\r","\\\"");
		$replace = array("\n", "\r","\"");
	    $r = str_replace($pattern, $replace, $str);
	    return $r;
	}
		
	function removeBreakLine($str) {
		$pattern = array("/\n/", "/\r/");
		$replace = array(" "," ");
	    $r = preg_replace($pattern, $replace, $str);
	    return $r;
	}
	
	function addMFilter($s,$f) {
		if (count($s)>1) {
			$v = " (".$f." = ".util::str($s[0]);
			for ($i=1;$i<count($s);$i++) {
				$v .= " OR ".$f." = ".util::str($s[$i]);
			}
			$v.=")";
		} else {
			$v = " ".$f." = ".util::str($s);	
		}
		return $v;		
	}
	
	function addNotificationFile(&$notificationList,$team,$file,$prj,$sprj,$type) {
		if ($notificationList[$team]==null) {
			$notificationList[$team]=array();
		}
		$elem = array("file" => $file,"prj" => $prj,"sprj" => $sprj,"type"=>$type);
		array_push($notificationList[$team],$elem);
	}
	
	function notifyListUpdate($notificationList) {
		global $loader;
		global $_log;
		
		foreach ($notificationList as $teamid => $elem) {
			$_log->info("Notify team $teamid");
			$u = new user;
			$u->teamid=$teamid;
			$u->groupid=GROUP_COORD;
			$u->status=STATUS_ACTIVE;
			$list = $loader->loadListBy($u,$u->listByFilters());
			
			foreach ($list as $user) {
				$pr = new preferences;
				$pr->userid=$user->userid;
				$pr->id="1003";
				$r = $loader->get($pr);
				if (!$r) {
					$filetext = s("* {0} [{1}] -{2}-",$user->lang,true);
					$sub = s("The file list was updated",$user->lang,true);	
					$addf="";
					$rmf="";
					foreach ($elem as $el) {
						foreach ($el['file'] as $fl) {
							$ar=array();
							$ar[]=$fl->name;
							$ar[]=$el['sprj'];
							$ar[]=$el['prj'];
							if ($el['type']=="rm") {
								if ($rmf!="") $rmf.="\n";
								$rmf .= String::format($filetext,$ar);
							} else {
								if ($addf!="") $addf.="\n";
								$addf .= String::format($filetext,$ar);
							}
						}
					}
					$subtext = "";
					if ($addf!="") {
						$subtext = String::format(s("Files added:\n\n{0}",$user->lang,true),$addf);
					}
					if ($rmf!="") {
						if ($subtext!="") $subtext .= "\n\n";
						$subtext .= String::format(s("Files removed:\n\n{0}",$user->lang,true),$rmf);
					}				
					$text = String::format(s("The following modifications were done to the file list:\n\n{0}",$user->lang,true),$subtext);
					@sendMail($user->mail,$sub,$text);
				}
			}
		}		
	}
			
?>
